import router from "@/router"
import { authorizationSetting } from "@/settings/authorization-setting"
import { md5 } from "js-md5"
import { api } from "./api"
import { MenuState, useAuthStore } from "@/store/modules/auth"
import { useAppStore } from "@/store/modules/app"
import { isEmpty } from "@/utils"
import { useRouteStore } from "@/store/modules/route"

/**
 * 权限相关配置
 */
export interface AuthorizationSetting {
    /**
     * token请求头前缀
     */
    tokenPrefix: string
    /**
     * token
     */
    accessToken: string
    /**
     * refresh token
     */
    refreshToken: string
}

/**
 * 登录成功，后端返回的数据结构
 */
export interface AuthResponse {
    accessToken: string
    refreshToken: string
    username: string
    avatar?: string
    gender?: string
    welcome?: string
    permissions: string[]
    menus: MenuState[]
}

/**
 * 本地存储Token
 */
export const useAccessToken = createGlobalState(() => useStorage<null | string>(authorizationSetting.accessToken, null))
export const useRefreshToken = createGlobalState(() => useStorage<null | string>(authorizationSetting.refreshToken, null))

/**
 * 发起Http请求设置请求头
 */
export const authorizationHeader = authorizationSetting.accessToken
export const authorizationValue = () => {
    const token = useAccessToken()
    return isEmpty(token.value) ? undefined : authorizationSetting.tokenPrefix + token.value
}

/**
 * 登录
 */
export const doLogin = async (username: string, password: string) => {
    const { res, isOk } = await api.login({ username, password: md5(password) })
    if (isOk()) {
        const data = res.value as AuthResponse
        registerLoginInfo(data)
        const appStore = useAppStore()
        // @ts-ignore
        window["$notification"].success({
            title: "登录成功",
            content: "欢迎使用" + appStore.setting?.name,
            duration: 3000
        })
        route2HomePage(false)
    }
}

/**
 * 登出
 */
export const doLogout = async () => {
    const { isOk } = await api.logout()
    if (isOk()) {
        clearLoginInfo()
        backToLoginPage(false)
    }
}

/**
 * 验证 Token
 */
export const checkToken = async () => {
    const { res, isOk } = await api.checkToken()
    if (isOk()) {
        const data = res.value as AuthResponse
        registerLoginInfo(data)
    }
}

const registerLoginInfo = (data: AuthResponse) => {
    const authStore = useAuthStore()
    const accessToken = useAccessToken()
    const refreshToken = useRefreshToken()
    accessToken.value = data.accessToken
    refreshToken.value = data.refreshToken
    const user = { name: data.username, avatar: data.avatar, gender: data.gender }
    authStore.login(user, data.permissions, data.menus)
}

/**
 * 清理登录信息
 * 1、清理 Token
 * 2、清理 Store
 */
export const clearLoginInfo = () => {
    const authStore = useAuthStore()
    const accessToken = useAccessToken()
    const refreshToken = useRefreshToken()
    const routeStore = useRouteStore()
    authStore.logout()
    routeStore.clear()
    accessToken.value = null
    refreshToken.value = null
}

export const backToLoginPage = (replace: boolean = false) => {
    if (replace) {
        router.replace("/login")
    } else {
        router.push("/login")
    }
}

export const route2HomePage = (replace: boolean = false) => {
    if (replace) {
        router.replace("/")
    } else {
        router.push("/")
    }
}
